﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Maps.MapControl;
using Phone7ActionPack.Controls;

namespace Phone7ActionPack.BingMaps
{
    //
    // If you want your Action to target elements other than its parent, extend your class
    // from TargetedTriggerAction instead of from TriggerAction
    //
    public class LocationChangedCenterMapAction : TargetedTriggerAction<DependencyObject>
    {
        private static Phone7ActionPack.BingMaps.ValueConverters.GeoCoordinateMapLocationValueConverter converter;
        private System.Device.Location.GeoCoordinate coord;
             
        public LocationChangedCenterMapAction()
        {
            
        }
        protected override void OnAttached()
        {
            isValidAttachment(this.AssociatedObject);
            base.OnAttached();
            
            converter = new ValueConverters.GeoCoordinateMapLocationValueConverter();
        }

        private void isValidAttachment(DependencyObject obj)
        {
            var locationControl = obj as LocationControl;
            if (locationControl != null)
                this.coord = locationControl.GeoCoordinate;
            else // this is not a LocationControl or a control that extends the LocationControl
            {
                var locationVisualControl = obj as LocationVisualControl;
                if (locationVisualControl != null)
                    this.coord = locationControl.GeoCoordinate;
                else // this is not a LocationVisualControl or a control that extends the LocationVisualControl 
                    throw new Exception(string.Format(Resources.Strings.AssociatedObjectIsNotLocationControl, obj.GetType().Name));
            }
        }
        private void centerMap()
        {
            (this.Target as Map).Center = (Location)converter.Convert(this.coord, typeof(Location), null, null);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }
        protected override void Invoke(object o)
        {
            isValidAttachment(this.AssociatedObject);
            //throw new Exception("");
            if (this.Target.GetType() == typeof(Map))
                centerMap();
        }
    }
}